<template>
	<view class="bg-white">
		<cu-custom :isFromOutside="isFromOutSide" :isBack="true">
			<block slot="backText">{{isFromOutSide?'首页':'返回'}}</block>
			<block slot="content">{{navTitle}}</block>
		</cu-custom>
		<mescroll-body ref="mescrollRef" @init="mescrollInit" @down="downCallback" :up="upOption">
			<view v-for="(item,index) in gridList" :key="index">
				<view @tap="jumpToPostList(item)"
					class="flex align-center justify-between padding-top padding-bottom solid-bottom">
					<view class="flex justify-start align-center">
						<view class="flex justify-start align-center padding-left-xl">
							<image class="radius" :src="item.icon" style="width: 45upx;height: 45upx;">
							</image>
						</view>
						<view class="flex justify-start align-center padding-left-xl">
							<text class="text-black title">{{item.name}}</text>
							<view v-if="item.goods_id>0&&isIOS==false" class="padding-left-xs">
								<view class="cu-tag tipLabel bg-red">付费</view>
							</view>
							<view v-if="item.need_auth==1" class="padding-left-xs">
								<view class="cu-tag tipLabel bg-purple">授权</view>
							</view>
							<view v-if="item.can_access_user_group&&item.can_access_user_group.length>0" class="padding-left-xs">
								<view class="cu-tag tipLabel bg-blue">分组</view>
							</view>
						</view>
					</view>
					<view v-if="isPublishChoose" class="padding-right-lg">
						<button @tap.stop="chooseForum(item)" class="cu-btn bg-green radius">选择</button>
					</view>
					<view @tap.stop="subscribeAction(item,index)" v-else class="flex justify-center align-center padding-right-lg" style="flex-direction: column;">
						<image
							:src="'../../../static/images/setting/forum_'+[item.is_subscribe?'unsubscribe.png':'subscribe.png']"
							style="width: 35upx;height: 35upx;"></image>
						<view style="height: 2upx;"></view>
						<view 
							class="actionBtn">{{item.is_subscribe?'取消':'订阅'}}</view>
					</view>
				</view>
			</view>
		</mescroll-body>
	</view>
</template>

<script>
	import MescrollMixin from "@/components/mescroll-uni/mescroll-mixins.js";
	import {
		getMySubscribeList,
		getForumList,
		subscribe,
		unsubscribe,
		getUserPublishForumList,
		buySubscribe,
		asyncCheckOrder
	} from '@/api/api.js'
	import config from '@/api/config.js'
	import {
		isSubscribeTipReadStatusOk,
		saveSubscribeTipReadStatus
	} from '@/api/statusCache.js'
	import {
		isLogin,
		getUserInfo
	} from '@/api/auth.js'
	import {
		checkLogin
	} from '@/js_sdk/checkLogin.js'
	export default {
		mixins: [MescrollMixin],
		data() {
			return {
				isFromOutSide:false,
				onlyAuth: false,
				isIOS: this.IsIOS,
				isMySubcribe: false,
				isPublishChoose: false,
				gridList: [],
				gridCol: 3,
				upOption: {
					use: true,
					page: {
						size: 10 // 每页数据的数量,默认10
					},
					textNoMore: config.customNoMore,
					noMoreSize: 1, // 配置列表的总数量要大于等于5条才显示'-- END --'的提示
					empty: {
						tip: '还没有订阅，快去订阅吧~'
					}
				}
			}
		},
		onLoad(options) {
			let scene = uni.getStorageSync('AppLaunchFromTimeline')
			if (scene !== null && scene !== undefined && scene !== "") {
				this.isFromOutSide = true
			}
			if(options.outside !== null && options.outside !== undefined) {
				this.isFromOutSide = true
			}
			if (options.isPublish !== null && options.isPublish !== undefined) {
				this.isPublishChoose = true
				if (options.onlyAuth !== null && options.onlyAuth !== undefined) {
					this.onlyAuth = true
				}
			}
			if (options.isMy !== null && options.isMy !== undefined) {
				this.isMySubcribe = true
			}
		},
		computed: {
			navTitle() {
				if (this.isMySubcribe) {
					return '我的订阅'
				}
				if (this.isPublishChoose) {
					return '选择板块'
				}
				return '订阅'
			}
		},
		methods: {
			onShareAppMessage(res) {
				return {
					title: config.forumShareTitle,
					path: '/pages/always/forum-list/forum-list?outside=1'
				}
			},
			onShareTimeline(res) {
				return {
					title: config.forumShareTitle,
					path: '/pages/always/forum-list/forum-list?outside=1'
				}
			},
			jumpToPostList(item) {
				let userInfo = getUserInfo()
				//管理员以上无限制
				if (userInfo.role_id > 0) {
					if (item.page_path && item.page_path.length > 0 && item.page_path.indexOf('/pages') !== -1) {
						uni.navigateTo({
							url: item.page_path
						})
					} else {
						uni.navigateTo({
							url: '/pages/lessuse/forum-post-list/forum-post-list?forumId=' + item.forum_id +
								'&forumName=' + item.name
						})
					}
					return
				}

				if (item.is_subscribe == 0) {
					if (item.need_auth == 1) {
						if (isLogin() == true) {
							uni.showModal({
								title: '此板块需要授权订阅后才可以查看'
							})
						} else {
							uni.showModal({
								title: '权限提示',
								content: '此板块需要授权才可以查看，是否立即登录同步权限?',
								confirmText: '立即登录',
								success(res) {
									if (res.confirm) {
										checkLogin()
									}
								}
							})
						}
						return
					}
					if (item.goods_id > 0) {
						if (this.isIOS) {
							uni.showModal({
								title: '由于相关规范，iOS功能暂不可用'
							})
						} else {
							if (isLogin()) {
								uni.showModal({
									title: '此板块需要付费订阅后才可以查看'
								})
							} else {
								uni.showModal({
									title: '权限提示',
									content: '此板块需要付费才可以查看,是否立即登录同步权限?',
									confirmText: '立即登录',
									success(res) {
										if (res.confirm) {
											checkLogin()
										}
									}
								})
							}
						}
						return
					}
					//是不是有分组访问权限的
					if (item.can_access_user_group && item.can_access_user_group.length > 0) {
						//是不是发帖组成员，是的话默认可以进入访问
						let canAccess = false
						if (item.can_post_user_group && item.can_post_user_group.length > 0) {
							let postGroupList = item.can_post_user_group.split(';')
							if (postGroupList.indexOf(userInfo.group_id) !== -1) {
								canAccess = true
							}
						}
						if (canAccess == false) {
							let accessGroupList = item.can_access_user_group.split(';')
							if (accessGroupList.indexOf(userInfo.group_id) !== -1) {
								canAccess = true
							}
						}
						if (canAccess == false) {
							if (isLogin() == false) {
								uni.showModal({
									title: '权限提示',
									content: '此板块需要指定用户组才可以查看，是否立即登录同步权限?',
									confirmText: '立即登录',
									success(res) {
										if (res.confirm) {
											checkLogin()
										}
									}
								})
							} else {
								uni.showModal({
									title: '您当前所在用户组无权访问此版块!'
								})
							}
							return
						}
					}
				}

				if (item.page_path && item.page_path.length > 0 && item.page_path.indexOf('/pages') !== -1) {
					uni.navigateTo({
						url: item.page_path
					})
				} else {
					uni.navigateTo({
						url: '/pages/lessuse/forum-post-list/forum-post-list?forumId=' + item.forum_id +
							'&forumName=' + item.name
					})
				}
			},
			downCallback() {
				this.initForumList()
			},
			chooseForum(item) {
				const eventChannel = this.getOpenerEventChannel()
				eventChannel.emit('finishChoose', item);
				uni.navigateBack({
					delta: 1
				})
			},
			realBuySubscribe(item, index) {
				buySubscribe(item.forum_id).then(res => {
					//已经创建订单成功，可以清除了
					console.log('server request param:' + JSON.stringify(res))
					let orderNo = res.data.orderNo

					let that = this
					//拉起支付
					uni.requestPayment({
						provider: 'wxpay',
						timeStamp: res.data.timeStamp,
						nonceStr: res.data.nonceStr,
						package: res.data.package,
						signType: res.data.signType,
						paySign: res.data.paySign,
						complete(res) {
							console.log('pay complete:' + JSON.stringify(res))
						},
						success: function(res) {
							console.log('pay success:' + JSON.stringify(res.data));
							uni.$emit('SubscribeForumChanged')
							that.gridList[index].is_subscribe = 1 //更新状态
							uni.hideLoading()
							uni.showModal({
								title: '购买提示',
								content: '下单成功，是否前往“我的订单”查看?',
								cancelText: '取消',
								confirmText: '前往查看',
								success: (res) => {
									if (res.confirm) {
										uni.navigateTo({
											url: '/pages/always/order-list/order-list?tab=1'
										})
									}
								}
							})
						},
						fail: function(err) {
							//可能已经支付完成，但是遇到报错，尝试刷新订单状态
							asyncCheckOrder(orderNo).then(res => {
								console.log('async check order req success:' + JSON.stringify(
									res))
							}).catch(error => {
								console.log('async check order req fail:' + JSON.stringify(
									error))
							})
							//支付失败，跳转我的订单页面继续支付
							console.log('pay fail:' + JSON.stringify(err));
							uni.hideLoading()
							uni.showModal({
								title: '订单支付提示',
								content: '订单创建成功，链接微信支付失败，是否前往“我的订单”继续完成支付',
								cancelText: '取消',
								confirmText: '继续支付',
								success: (res) => {
									if (res.confirm) {
										uni.navigateTo({
											url: '/pages/always/order-list/order-list?tab=0'
										})
									}
								}
							})
						}
					});
				}).catch(error => {
					uni.hideLoading()
					//是不是微信请求失败，是的话跳转订单页继续
					if (error.code == 30022) {
						this.clearOrderFormInfo()
						//不要重复支付
						uni.showModal({
							title: '订单支付提示',
							content: '该订单已经完成支付，请刷新列表检查订单状态',
							confirmText: '知道了'
						})
					}
					if (error.code == 30021) {
						uni.showModal({
							title: '订单支付提示',
							content: '订单创建成功，链接微信支付失败，是否前往“我的订单”继续完成支付',
							cancelText: '取消',
							confirmText: '继续支付',
							success: (res) => {
								if (res.confirm) {
									uni.navigateTo({
										url: '/pages/always/order-list/order-list?tab=0'
									})
								}
							}
						})
					}
				})
			},
			buySubscribeAction(item, index) {
				if (this.isIOS) {
					uni.showModal({
						title: '由于相关规范，iOS功能暂不可用'
					})
					return
				}
				let that = this
				uni.showModal({
					title: '订阅提示',
					content: item.buy_tip,
					confirmText: '继续订阅',
					success(res) {
						if (res.confirm) {
							that.realBuySubscribe(item, index)
						}
					}
				})
			},
			realSubscribe(item, index) {
				uni.showLoading({
					title: '正在提交...'
				})
				if (item.is_subscribe == 1) {
					unsubscribe(item.forum_id).then(res => {
						uni.hideLoading()
						uni.$emit('SubscribeForumChanged')
						this.gridList[index].is_subscribe = 0
						uni.showToast({
							title: '取消订阅成功!'
						})
					}).catch(error => {
						uni.hideLoading()
						uni.showToast({
							icon: 'none',
							title: '取消订阅失败!'
						})
					})
				} else {
					subscribe(item.forum_id).then(res => {
						uni.hideLoading()
						uni.$emit('SubscribeForumChanged')
						this.gridList[index].is_subscribe = 1
						uni.showToast({
							title: '订阅成功!'
						})
						let isReadTipOk = isSubscribeTipReadStatusOk()
						if (isReadTipOk == false) {
							uni.showModal({
								title: '订阅提示',
								content: '订阅之后，您关心的内容将会出现在首页',
								confirmText: '去首页',
								success(res) {
									if (res.confirm) {
										uni.reLaunch({
											url: '/pages/index/index?tab=3'
										})
									}
								}
							})
							saveSubscribeTipReadStatus()
						}
					}).catch(error => {
						uni.hideLoading()
						uni.showToast({
							icon: 'none',
							title: '订阅失败!'
						})
					})
				}
			},
			authSubscribe(item, index) {
				uni.navigateTo({
					url: '/pages/always/subscribe-voucher-list/subscribe-voucher-list'
				})
			},
			subscribeAction(item, index) {
				if (isLogin() == false) {
					checkLogin()
					return
				}
				//管理员以上无限制
				let isNotAdmin = getUserInfo().role_id < 1
				if (item.goods_id > 0 && item.is_subscribe == 0 && isNotAdmin) {
					this.buySubscribeAction(item, index)
					return
				}
				if (item.need_auth == 1 && item.is_subscribe == 0 && isNotAdmin) {
					let that = this
					uni.showModal({
						title: '解锁提示',
						content: '该板块需要授权码进行解锁，是否跳转《我领的券》界面进行解锁?',
						confirmText: '立即前往',
						success(res) {
							if (res.confirm) {
								that.authSubscribe(item, index)
							}
						}
					})
					return
				}
				if (item.goods_id > 0 && item.is_subscribe == 1 && isNotAdmin) {
					let that = this
					uni.showModal({
						title: '订阅提示',
						content: '付费板块取消订阅后需要重新购买,是否还要继续？',
						cancelText: '手滑了',
						confirmText: '取消订阅',
						success(res) {
							if (res.confirm) {
								that.realSubscribe(item, index)
							}
						}
					})
					return
				}
				if (item.need_auth == 1 && item.is_subscribe == 1 && isNotAdmin) {
					let that = this
					uni.showModal({
						title: '订阅提示',
						content: '授权板块取消订阅后需要重新授权,是否还要继续？',
						cancelText: '手滑了',
						confirmText: '取消订阅',
						success(res) {
							if (res.confirm) {
								that.realSubscribe(item, index)
							}
						}
					})
					return
				}
				this.realSubscribe(item, index)
			},
			initForumList() {
				uni.showLoading({
					title: '正在加载...'
				})
				if (this.isMySubcribe) {
					getMySubscribeList().then(res => {
						uni.hideLoading()
						this.gridList = res.data
						if (this.mescroll) {
							this.mescroll.endSuccess(this.gridList.length, false);
						}
					}).catch(error => {
						uni.hideLoading()
						uni.showToast({
							icon: 'none',
							title: '加载失败!'
						})
						if (this.mescroll) {
							this.mescroll.endErr();
						}
					})
				} else {
					if (this.isPublishChoose) {
						getUserPublishForumList().then(res => {
							uni.hideLoading()
							if (this.onlyAuth) {
								let list = []
								res.data.forEach(item => {
									if (item.need_auth == 1) {
										list.push(item)
									}
								})
								this.gridList = list
							} else {
								this.gridList = res.data
							}
							if (this.mescroll) {
								this.mescroll.endSuccess(this.gridList.length, false);
							}
						}).catch(error => {
							uni.hideLoading()
							uni.showToast({
								icon: 'none',
								title: '加载失败!'
							})
							if (this.mescroll) {
								this.mescroll.endErr();
							}
						})
						return
					}
					getForumList().then(res => {
						uni.hideLoading()
						if (isLogin() == false) {
							res.data.forEach(item => {
								item.is_subscribe = 0
							})
						}
						this.gridList = res.data
						if (this.mescroll) {
							this.mescroll.endSuccess(this.gridList.length, false);
						}
					}).catch(error => {
						uni.hideLoading()
						uni.showToast({
							icon: 'none',
							title: '加载失败!'
						})
						if (this.mescroll) {
							this.mescroll.endErr();
						}
					})
				}
			}
		}
	}
</script>

<style lang="scss" scoped>
	.actionBtn {
		color: #8cbcff;
		font-size: 20upx;
	}

	.title {
		font-size: 34upx;
	}

	.tipLabel {
		border-radius: 200upx;
		font-size: 20upx;
		padding: 0upx 10upx;
		height: 28upx;
		color: #ffffff;
	}
</style>
